<template>
    <a-card class="customer-label-page" :bodyStyle="{padding: '0px 20px 20px'}">
        <a-tabs v-model:activeKey="activeKey">
            <a-tab-pane key="1" tab="手动标签">
                <a-alert message="配置手动标签后，企业员工可以为客户打上标签" type="warning" show-icon />
                <a-layout class="mt-[8px]" style="height: calc(100vh - 255px);background-color:#fff;">
                    <!-- 左侧 -->
                    <a-layout-sider width="300px" style="border: 1px solid #eee;padding: 10px 0;" theme="light">
                        <h4 style="font-weight:600;margin-left:10px;">全部标签组</h4>
                        <ul style="overflow: auto;height: calc(100% - 22px);scrollbar-width: none;">
                            <li v-for="item in groupList" :key="item.id" 
                                class="item-container group-item flex justify-between items-center" 
                                :class="activedGroupId===item.id?'actived':''"
                                @click.stop.prevent="groupChange(item)"
                            >
                                <div class="content">
                                    <p>{{item.groupName}}</p>
                                    <p class="text-12 belong-to" :style="{visibility:item.defaultIn?'hidden':'visible'}">{{getGroupTypeText(item.groupType)}}</p>
                                </div>
                                <div v-if="!(item.builtIn || item.defaultIn)" class="handle">
                                    <a-button type="link" @click.stop="editGroup(item)">
                                        <template #icon><FormOutlined /></template>
                                    </a-button>
                                    <a-button danger type="link" @click.stop="delGroup(item)">
                                        <template #icon><DeleteOutlined /></template>
                                    </a-button>
                                </div>                                                
                            </li>                                                
                        </ul>
                    </a-layout-sider>

                    <!-- 右侧 -->
                    <a-layout-content class="ml-[4px] py-[20px] px-[10px]" style="border: 1px solid #eee;">
                        <!-- 筛选 -->
                        <div class="flex justify-between items-center mb-4">
                            <a-input-search
                                v-model:value="searchText"
                                placeholder="请输入标签名称"
                                class="search-style"
                                style="width: 200px"
                                allowClear
                                @search="onSearch"
                            />
                            <div>
                                <a-button type="primary" @click="addTags">新增标签</a-button>
                                <a-button class="ml-2" @click="addGroups">新增标签组</a-button>
                            </div>
                        </div>  

                        <!-- 列表 -->
                        <a-list :grid="{ gutter: 16, column: 4 }" :data-source="dataList" style="height:calc(100% - 80px);overflow-y:auto;overflow-x:hidden;">
                            <template #renderItem="{ item }">
                                <a-list-item>
                                    <a-spin size="small" :spinning="item.spinning?true:false">
                                        <a-card title="" class="item-container tag-item">
                                            <div class="content">
                                                <a-tooltip>
                                                    <template #title>标签名称：{{item.labelName}}</template>
                                                    <p>标签名称：{{item.labelName}}</p>
                                                </a-tooltip>
                                                <a-tooltip>
                                                    <template #title>标签组：{{item.groupName}}</template>
                                                    <p>标签组：{{item.groupName}}</p>
                                                </a-tooltip>
                                                
                                                <p>客户数：{{item.customerNum +'/'+ item.customerTotal}}</p>
                                                <p>线索数：{{item.clueNum +'/'+item.clueTotal}}</p>
                                                <p>创建时间：{{item.createAt ? item.createAt.substring(0,10) : '--'}}</p>
                                                <p>标签状态：
                                                    <a-switch size="small" :checked="!!item.usableFlag" @change="()=>changeStatus(item)"></a-switch>
                                                </p>
                                            </div>
                                            <div class="handle">
                                                <a-button type="link" @click.stop="editTags(item)">
                                                    <template #icon><FormOutlined /></template>
                                                </a-button>
                                                <a-button danger type="link" @click.stop="delTags(item)">
                                                    <template #icon><DeleteOutlined /></template>
                                                </a-button>
                                            </div>
                                        </a-card>                                    
                                    </a-spin>
                                </a-list-item>
                            </template>
                        </a-list>  

                        <!-- 分页 -->
                        <div class="text-right pt-[10px]">
                            <a-pagination
                                size="small"
                                :total="pagination.total"   
                                show-size-changer
                                show-quick-jumper
                                :page-size-options="['12', '24', '36']"
                                :show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
                                v-model:pageSize="pagination.size"
                                v-model:current="pagination.current"
                                @change="pageChange"
                            >
                                <template #buildOptionText="props">
                                    <span>{{ props.value }}条/页</span>
                                </template>
                            </a-pagination>
                        </div>   
                    </a-layout-content>
    
                </a-layout>
            </a-tab-pane>
        </a-tabs>
    </a-card>

    <!-- 新增/编辑标签组 -->
    <add-tag-groups-modal
        v-if="bindGroupVisible"
        v-model:visible="bindGroupVisible"
        :type="type"
        :callBack="customerLabelApi.submitForm"
        :info="rowInfo"
        @finished="()=>{
            getGroupList()
            if(rowInfo && rowInfo.id === activedGroupId) getPage()
        }"
    />

    <!-- 新增/编辑标签 -->
    <add-tags-modal
        v-if="bindVisible"
        v-model:visible="bindVisible"
        :type="type"
        :callBack="customerLabelApi.submitLabelForm"
        :info="rowInfo"
        :groupList="groupList"
        @finished="getPage"
    />
</template>

<script setup>

	import { useRouter } from 'vue-router'
    import { message, Modal } from 'ant-design-vue'

	import customerLabelApi from '@/api/biz/customerLabelApi'
    import addTagGroupsModal from './addTagGroupsModal.vue'
    import addTagsModal from './addTagsModal.vue'

	const router = new useRouter()

    onBeforeMount(() => {
		getGroupList().then(res => {
            activedGroupId.value = res[0].id
            getPage()
        })
	})

    /**
     * 公用
     *  */
    const activeKey = ref('1')
    const rowInfo = ref(null)
    const type = ref('new')

    /**
     * 适用对象
     *  */
    const groupTypeObject = {
        '0': '客户',
        '1': '线索',
    }

    const getGroupTypeText = (value) => {
        if(value){
            return value.split(',').reduce((labels, item) => {
                labels.push(groupTypeObject[item])
                return labels
            }, []).join('、')
        } else {
            return ''
        }

    }


    /**
     * 标签组操作
     *  */
    const groupList = ref([])
    const bindGroupVisible = ref(false);
    const activedGroupId = ref(null);

    const editGroup = (row) => {
        type.value = 'edit';
        rowInfo.value = row;
        bindGroupVisible.value = true;
    }
    const addGroups = () => {
        type.value = 'new';
        rowInfo.value = null;
        bindGroupVisible.value = true;
    }
    const delGroup = (row) => {
        Modal.confirm({
			title: '提示',
			content: '删除后该标签组下的标签将分组到默认分组，是否删除分组？',
			okText: '确认',
			onOk: () => {
				customerLabelApi.delete({ id: row.id }).then(() => {
					// message.success('删除成功')

                    getGroupList().then(res => {
                        // 删除选中时，默认第一个
                        if(activedGroupId.value === row.id){
                            activedGroupId.value = res[0].id
                            pagination.value.current = 1;
                            getPage()
                        }
                    })
				})
			},
			closable: true,
			cancelText: '取消'
		})            
    }
    const getGroupList = () => {
        return customerLabelApi.list().then((res) => {
            groupList.value = res;
            return res;
        })
    }
    const groupChange = (row) => {
        if(row.id === activedGroupId.value) return
        activedGroupId.value = row.id
        searchText.vallue = ''
        pagination.value.current = 1;
        
        getPage()
    }

    /**
     * 标签操作
     *  */
    const dataList = ref([])
    const pagination = ref({
		size: 12,
		current: 1,
		total: 0
	})
    const bindVisible = ref(false);
    const statusSpinning = ref(false)
    const addTags = () => { 
        type.value = 'new';
        rowInfo.value = {customerGroupId: activedGroupId.value};
        bindVisible.value = true;
    }
    const editTags = (row) => {
        type.value = 'edit';
        rowInfo.value = row;
        bindVisible.value = true;
    }
    const delTags = (row) => {
        Modal.confirm({
			title: '提示',
			content: '确认要删除该标签吗？删除后无法恢复',
			okText: '确认',
			onOk: () => {
				customerLabelApi.deleteLabel({ id: row.id }).then(() => {
					// message.success('删除成功')
                    if(pagination.value.current > 1 && dataList.value.length === 1){
                        pagination.value.current -= 1;
                    }
                    getPage()
				})
			},
			closable: true,
			cancelText: '取消'
		})                 
    }
    const changeStatus = (row) => {
        row.spinning = true
        customerLabelApi.updateStatus({ id: row.id, usableFlag: row.usableFlag ? 0 : 1}).then(() => {
            getPage()
        }).catch(() => {
            getPage()
        }).finally(() => {
            row.spinning = false
        })                
    }
    const pageChange = (cur, size) => {
		pagination.value.size = size
		pagination.value.current = cur
		getPage()
	}
    const getPage = () => {
        const params = {
            customerGroupId: activedGroupId.value,
            current: pagination.value.current,
            size: pagination.value.size
        };
        if(searchText.value && searchText.value !== ''){
            params.labelName = searchText.value
        }
        customerLabelApi.page(params).then((res) => {
            dataList.value = res.records;
            pagination.value.total = res.total
        })  
    }

    /**
     * 标签搜索
     *  */
    const searchText = ref('')
    const onSearch = () => {
        pagination.value.current = 1;
        getPage()
    }
    
    
</script>

<style scoped lang="less">
    .customer-label-page {
        p {
            margin-bottom: 2px;
        }
        ul>li{
            list-style: none;
        }
        .color-gray{
            color: gray;
        }
        .item-container {
            .handle {
                display: none;
                :deep(.ant-btn-icon-only){
                    font-size: 18px;
                }
            }
            .content {
                & > p{
                    text-overflow: ellipsis;
                    overflow: hidden;
                    white-space: nowrap;
                }
            }

            &:hover{
                .handle{
                    display: block;
                }
            }
        }

        .group-item {
            cursor: pointer;
            padding: 5px 20px;
            .content {
                max-width: calc(100% - 65px);
            }
            .handle {
                width: 65px;
            }
            .belong-to {
                color: gray
            }
            
            &:hover {
                background-color: rgba(0, 0, 0, 0.06);
            }  
            &.actived {
                background-color: #e6f4ff;
                color: var(--primary-color);
                .belong-to {
                    color: inherit
                }
            }   
        }

        .tag-item {
            position: relative;
            .handle{
                position: absolute;
                top: 0;
                right: 0;
            }
        }

        .search-style{
            :deep(.ant-input-affix-wrapper-focused){
                box-shadow: none;
            }
        }

    }
</style>
